# -*- coding: utf-8 -*-
# @File:     generate_share.py
# @Author:
# @DateTime: 2025/06/24/17:13
import datetime
import json
import time
from typing import Optional, Union, Any, List, Dict
from fastapi.encoders import jsonable_encoder
from sqlalchemy import or_
from sqlalchemy.orm import Session

from app.db.database import get_db
from app.models.system import Users
from app.utils import security
from app.utils.custom_exc import CustomException
from app.utils.custom_response import success_response, error_response
from fastapi import APIRouter, Query, Body, Path, Depends, UploadFile, Form, File, Request
from pydantic import BaseModel, Field

from app.models.generate import GenerateShare, GenerateResult, GenerateTask
from app.utils.curd_base import ModelCRUD
from app.utils.file_storage import get_storage_file, save_storage_file, delete_storage_file
from app.utils.utils import get_now_time_string

router = APIRouter()


class CRUDGenerateShareTask(ModelCRUD):

    model = GenerateShare

    @staticmethod
    def serializer(queryset, only: tuple = (), date_format: str = None, datetime_format: str = None,
                   time_format: str = None):

        li = []
        for instance in queryset:
            data_dict = instance.to_dict(only=only, date_format=date_format, datetime_format=datetime_format, time_format=time_format)
            data_dict['path_url'] = get_storage_file(instance.path)
            data_dict['menu_name'] = instance.menu.name if instance.menu else None
            li.append(data_dict)
        return li


class GenerateShareReqData(BaseModel):
    result_id: int = Field(description='结果id')


class CreateGenerateShareTask(BaseModel):
    path: str = Field(description='结果路径')
    file_type: Optional[str] = Field(default=None, description='文件类型')
    menu_id: Optional[int] = Field(default=None, description='菜单ID')
    params: Optional[str] = Field(default=None, description='提交的参数')
    examine: int = Field(description='审核', default=1)
    user_id: Optional[int] = Field(default=None, description='用户ID')


class ResGenerateShareTask(CreateGenerateShareTask):
    hot: Optional[int] = Field(default=None, description='热度')


@router.post("/generate_share", summary="生成分享", response_model=ResGenerateShareTask, name='生成分享')
async def user_membership(
    request: Request,
    *,
    db: Session = Depends(get_db),
    req_data: GenerateShareReqData,
    current_user: Users = Depends(security.verify_access_token),
) -> Any:

    result_id = req_data.result_id

    result = db.query(GenerateResult).filter(GenerateResult.id == result_id, GenerateTask.user_id == int(current_user.id)).first()
    if not result:
        return error_response(message='未找到数据')
    if result.is_share:
        return error_response(message='已经分享')

    data = {
        'path': result.path,
        'file_type': result.file_type,
        'menu_id': result.task.menu_id,
        'params': result.task.params,
        'user_id': current_user.id
    }

    crud = CRUDGenerateShareTask()

    instance = crud.create(db, data=CreateGenerateShareTask.validate(data))

    result.is_share = 1
    db.add(result)
    db.commit()
    db.refresh(result)
    return success_response(message='分享成功')


able_filter_list = [
    {'name': 'user_id', 'source_filed': 'user_id', 'lookup_expr': 'eq', 'label': '等于user', 'type': int, 'method': None, 'required': False},
    {'name': 'examine', 'source_filed': 'examine', 'lookup_expr': 'eq', 'label': '等于examine', 'type': int, 'method': None, 'required': False},
]


@router.get("/manage_generate_share", summary="管理生成分享", response_model=ResGenerateShareTask, name='管理生成分享')
async def user_membership(
    request: Request,
    *,
    db: Session = Depends(get_db),
    page: int = Query(1, description='页码', ge=1),
    page_size: int = Query(10, description='页面大小', le=50, ge=1),
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    order_by_fields = ('-id',)

    crud = CRUDGenerateShareTask()

    queryset, total = crud.get_page_queryset(db, page=page, page_size=page_size, req_data=request.query_params, able_filter_list=able_filter_list, order_by_fields=order_by_fields)
    only = ('id', 'path', 'file_type', 'params', 'examine', 'user_id', 'hot', 'create_time')
    items = crud.serializer(queryset, only=only, datetime_format='%Y-%m-%d %H:%M:%S')
    resp = {
        "list": items,
        'total': total
    }
    return success_response(data=resp)


class ManageShareReqData(BaseModel):
    share_id: int = Field(description='分享id')
    examine: int = Field(description='审核')


@router.post("/manage_generate_share", summary="管理生成分享", response_model=ResGenerateShareTask, name='管理生成分享')
async def user_membership(
    request: Request,
    *,
    db: Session = Depends(get_db),
    req_data: ManageShareReqData,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    share_id = req_data.share_id
    examine = req_data.examine

    share = db.query(GenerateShare).filter(GenerateShare.id == share_id).first()
    if not share:
        return error_response(message='未找到数据')
    share.examine = examine
    db.add(share)
    db.commit()
    db.refresh(share)
    return success_response(message='审核成功')


@router.get("/get_generate_share", summary="获取生成分享", response_model=ResGenerateShareTask, name='获取生成分享')
async def user_membership(
        request: Request,
        *,
        db: Session = Depends(get_db),
        page: int = Query(1, description='页码', ge=1),
        page_size: int = Query(10, description='页面大小', le=50, ge=1),
        # current_user: Users = Depends(security.verify_access_token),
) -> Any:
    order_by_fields = ('-id',)

    crud = CRUDGenerateShareTask()

    queryset = crud.queryset(db=db).filter(GenerateShare.examine == 2)

    queryset = crud.order_by(queryset, order_by_fields)

    queryset, total = crud.get_queryset_pagination(queryset, page=page, page_size=page_size)
    only = ('id', 'path', 'file_type', 'params', 'user_id', 'hot', 'create_time')
    # items = crud.serializer(queryset, only=only, datetime_format='%Y-%m-%d %H:%M:%S')

    li = []
    for instance in queryset:
        data_dict = instance.to_dict(only=only, datetime_format='%Y-%m-%d %H:%M:%S')
        data_dict['menu_name'] = instance.menu.name if instance.menu else None
        data_dict['path_url'] = get_storage_file(instance.path)
        data_dict['user_username'] = instance.user.username
        li.append(data_dict)
    resp = {
        "list": li,
        'total': total
    }
    return success_response(data=resp)


